#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author  gikieng.li
# @Date    2017-02-25 10:19
import time

from common.runtime import RunTime
from config.mq_conf import OfflineBeanstalkConf, GsxtClueBeanstalkConf
from mq.mq_factory import MQFactory
from proxy.proxy_handler import ProxyHandler
from proxy.proxy_requests import ProxyRequests


class TaskBase(object):
    def __init__(self, log):
        self.log = log
        # 默认代理句柄
        self.__proxy_handler = ProxyHandler(log)
        # 默认消息队列句柄
        self.__beanstalk_handler = MQFactory.get_offline_beanstalk_handler(self.log)

        # 请求代理session
        self._proxy_requests = ProxyRequests(self.__proxy_handler, self.log)

        # 运行时控制，防止多个进程重入
        self.__run_time = RunTime(log)

    def __del__(self):
        if self.__beanstalk_handler is not None:
            self.__beanstalk_handler.close()

        if self.__proxy_handler is not None:
            self.__proxy_handler.close()

    # 重新初始化消息队列
    def _reset_beanstalk_handler(self, beanstalk_handler):
        """
        重新初始化消息队列，替换默认消息队列
        :param beanstalk_handler:
        :return:
        """
        self.__beanstalk_handler = beanstalk_handler

    # 获得代理句柄
    def _get_proxy_handler(self):
        return self.__proxy_handler

    # 获得动态代理
    def get_dynamic_proxy(self, host):
        """
        返回一个动态代理
        :param host: 当前采集站点域名
        :return: {"http": "http://10.10.10.10:8888"}
        """
        return self.__proxy_handler.get_dynamic_proxy(host)

    # 获取静态代理
    def get_static_proxy(self):
        """
        返回一个静态代理
        :return: {"http": "http://10.10.10.10:8888"}
        """
        return self.__proxy_handler.get_static_proxy()

    # 存储采集数据
    def push_offline_crawl_data(self, host, field, item):
        """
        发送数据到离线采集消息队列
        :param field: 当前采集站点板块名
        :param host: 当前采集站点域名
        :param tube: 需要发送的消息队列名称
        :param item: 发送的数据类型是dict
        :return:
        """
        if not isinstance(item, dict):
            raise Exception("发送数据格式错误: item type = {}".format(type(item)))
        if host is None or field is None:
            raise Exception("没有填写 host:{} 或者 field:{} ".format(host, field))

        item["host"] = host
        item["field"] = field

        return self.__push_data(OfflineBeanstalkConf.TUBE, item)

    def __push_data(self, tube, item):
        """
        发送数据到消息队列
        :param tube: 队列名
        :param item: 数据项
        :return:
        """
        return self.__beanstalk_handler.push_msg(tube, item)

    # 存储工商线索
    def push_gsxt_clue_data(self, item):
        '''
        发送数据到工商线索线索队列
        :param item: 线索数据包
        :return:
        '''
        if not isinstance(item, dict):
            raise Exception("发送数据格式错误: item type = {}".format(type(item)))
        return self.__push_data(GsxtClueBeanstalkConf.TUBE, item)

    def __call__(self, *args, **kwargs):
        start_time = time.time()
        self.start(*args, **kwargs)
        self.log.info("任务耗时: {} s".format(time.time() - start_time))

    def start(self, *args, **kwargs):
        """
        启动入口，需要继承
        :param args:
        :param kwargs:
        :return:
        """
        raise NotImplemented()
